package cn.kgc.springmvc.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author: mosin
 * @version: v1.0  2022/10/17
 * 基础的servlet  通过反射实现请求的分发
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 编码格式的处理可以放在过滤器中编写
        req.setCharacterEncoding("utf-8");
        //获取请求的方法名  add   反射  invoke（object，args）
        String method = req.getParameter("method");
        // 调用请求对应的servlet中的method方法  请求类的类对象象

        Class clazz = this.getClass();
        try {
            Method declaredMethod = clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.setAccessible(true);
            declaredMethod.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
